package com.wenx.message;

import java.util.*;
import java.util.stream.Collectors;

import static java.util.Comparator.comparingInt;

/**
 * Created by wenx on 2019-08-26 19:41
 */
public class Test {

    private static Message[] messages = {
            new Message("aa",1),
            new Message("aa",2),
            new Message("aa",3),
            new Message("aa",3),
            new Message("aa",4),
            new Message("aa",5),
            new Message("bb",3),
            new Message("bb",5),
            new Message("bb",6)
    };

    private static int[] order = {1,3,5};

    private static Message[] demo(Message[] messages, int[] order) {
        Map<String, Optional<Message>> collect = Arrays.stream(messages)
                .filter(message -> Arrays.stream(order).anyMatch(i -> i == message.getType()))
                .collect(Collectors.groupingBy(Message::getMobile, Collectors.minBy(comparingInt(Message::getType))));
        List<Message> result = new ArrayList<>();
        collect.forEach((k,v) -> {
            Message message = new Message();
            message.setMobile(k);
            message.setType(v.get().getType());
            result.add(message);
        });
        return result.toArray(new Message[0]);
    }

    private static Message[] demo2(Message[] messages, int[] order) {

        Map<String,Message> resultMap = new HashMap<>();

        for(Message message : messages) {
            for(int in : order) {
                if(message.getType() == in) {
                    Message ms = resultMap.get(message.getMobile());
                    if(ms != null) {
                        if(ms.getType() > in) {
                            resultMap.put(message.getMobile(),message);
                        }
                    } else {
                        resultMap.put(message.getMobile(),message);
                    }
                }
            }
        }
        List<Message> result = new ArrayList<>();
        resultMap.forEach((k,v) -> {
            Message message = new Message();
            message.setMobile(k);
            message.setType(v.getType());
            result.add(message);
        });
        return result.toArray(new Message[0]);
    }

    public static void main(String[] args) {

        Message[] demo = demo2(messages, order);
        Arrays.stream(demo).forEach(message -> System.out.println("message = " + message.getMobile() + " " + message.getType()));
    }

}